package org.zdw.data.structure.abc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ABC1 {

    private static Lock lock = new ReentrantLock();
    private static int count = 0;
    private static Condition A = lock.newCondition();
    private static Condition B = lock.newCondition();
    private static Condition C = lock.newCondition();

    static class ThreadA extends Thread{
        @Override
        public void run() {
            lock.lock();
            try {
                for (int i=0;i<10;i++){
                    while (count%3 != 0){
                        A.await();
                    }
                    System.out.println("A");
                    count++;
                    B.signal();
                }
            }catch (Exception e){}
            finally {
                lock.unlock();
            }
            super.run();
        }
    }

    static class ThreadB extends Thread{
        @Override
        public void run() {
            lock.lock();
            try {
                for (int i=0;i<10;i++){
                    while (count%3 != 1){
                        B.await();
                    }
                    System.out.println("B");
                    count++;
                    C.signal();
                }
            }catch (Exception e){}
            finally {
                lock.unlock();
            }
            super.run();
        }
    }

    static class ThreadC extends Thread{
        @Override
        public void run() {
            lock.lock();
            try {
                for (int i=0;i<10;i++){
                    while (count%3 != 2){
                        C.await();
                    }
                    System.out.println("C");
                    count++;
                    A.signal();
                }
            }catch (Exception e){}
            finally {
                lock.unlock();
            }
            super.run();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        new ThreadA().start();
        new ThreadB().start();
        ThreadC threadC = new ThreadC();
        threadC.start();
        threadC.join();
        System.out.println(count);
    }
}
